using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.ServiceModules;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.MiddlewareModules;
using System.Text;
using System.Diagnostics;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Configuration
{
    /// <summary>
    /// 简化的程序启动配置管理器
    /// 通过模块化管理所有服务和中间件配置
    /// </summary>
    public static class SimplifiedProgramConfigurator
    {
        /// <summary>
        /// 配置所有服务模块
        /// </summary>
        /// <param name="builder">Web应用程序构建器</param>
        /// <returns>配置后的构建器</returns>
        public static WebApplicationBuilder ConfigureServices(WebApplicationBuilder builder)
        {
            var startupStopwatch = Stopwatch.StartNew();
            Infrastructure.Configuration.StartupLogger.LogStartupMilestone("开始模块化服务配置");

            // 设置控制台编码
            Console.OutputEncoding = Encoding.UTF8;

            // Load additional configuration files
            LoadAdditionalConfigurationFiles(builder);
            Infrastructure.Configuration.StartupLogger.LogStartupMilestone("额外配置文件加载完成");

            // 初始化配置访问器
            ConfigurationAccessor.Initialize(builder.Configuration);
            Infrastructure.Configuration.StartupLogger.LogStartupMilestone("配置访问器初始化完成");

            // 检查启动模式
            var isFastStartup = StartupOptimizations.IsFastStartupEnabled(builder.Configuration) 
                               || string.Equals(builder.Environment.EnvironmentName, "Fast", StringComparison.OrdinalIgnoreCase)
#if FAST_START
                               || true
#endif
                               ;

            StartupLogger.LogStartupMilestone($"启动模式: {(isFastStartup ? "快速" : "标准")}");

            // 注册所有服务模块
            ServiceModuleRegistry.RegisterAllModules(builder.Services, builder.Configuration, isFastStartup);

            // 如果是开发环境且启用Swagger，则配置Swagger
            if (builder.Environment.IsDevelopment() && builder.Configuration.GetValue<bool>("Swagger:Enabled"))
            {
                var swStopwatch = Stopwatch.StartNew();
                ConfigureSwagger(builder);
                swStopwatch.Stop();
                StartupLogger.LogStartupMilestone($"Swagger 配置完成，耗时: {swStopwatch.ElapsedMilliseconds}ms");
            }

            startupStopwatch.Stop();
            StartupLogger.LogStartupMilestone($"服务配置完成，总耗时: {startupStopwatch.ElapsedMilliseconds}ms");

            return builder;
        }

        /// <summary>
        /// 配置所有中间件模块
        /// </summary>
        /// <param name="app">Web应用程序</param>
        /// <returns>配置后的应用程序</returns>
        public static WebApplication ConfigureMiddleware(WebApplication app)
        {
            var middlewareStopwatch = Stopwatch.StartNew();
            StartupLogger.LogStartupMilestone("开始模块化中间件配置");

            // 配置所有中间件模块
            MiddlewareModuleRegistry.ConfigureAllModules(app, app.Configuration);

            // 如果不是快速启动模式且启用Swagger，则配置Swagger中间件
            var isFastStartup = StartupOptimizations.IsFastStartupEnabled(app.Configuration);
            if (!isFastStartup && app.Configuration.GetValue("Swagger:Enabled", app.Environment.IsDevelopment()))
            {
                var swStopwatch = Stopwatch.StartNew();
                ConfigureSwaggerMiddleware(app);
                swStopwatch.Stop();
                StartupLogger.LogStartupMilestone($"Swagger 中间件配置完成，耗时: {swStopwatch.ElapsedMilliseconds}ms");
            }

            middlewareStopwatch.Stop();
            StartupLogger.LogStartupMilestone($"中间件配置完成，总耗时: {middlewareStopwatch.ElapsedMilliseconds}ms");

            return app;
        }

        /// <summary>
        /// 完成应用程序初始化
        /// </summary>
        /// <param name="app">Web应用程序</param>
        /// <param name="startupStopwatch">启动计时器</param>
        public static void FinalizeConfiguration(WebApplication app, Stopwatch startupStopwatch)
        {
            // 初始化启动日志器
            StartupLogger.Initialize(app.Services);

            // 配置应用程序关闭时的清理
            var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
            lifetime.ApplicationStopping.Register(() => 
            {
                EnhancedSerilogConfigurator.CloseSerilog();
            });

            startupStopwatch.Stop();
            StartupLogger.LogStartupSuccess(startupStopwatch.Elapsed);
        }

        /// <summary>
        /// 配置Swagger服务
        /// </summary>
        /// <param name="builder">Web应用程序构建器</param>
        private static void ConfigureSwagger(WebApplicationBuilder builder)
        {
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo 
                { 
                    Title = "JGSY CMS LowCode Platform API", 
                    Version = "v1" 
                });

                // 添加JWT认证支持
                c.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    In = Microsoft.OpenApi.Models.ParameterLocation.Header,
                    Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });

                c.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
                {
                    {
                        new Microsoft.OpenApi.Models.OpenApiSecurityScheme
                        {
                            Reference = new Microsoft.OpenApi.Models.OpenApiReference
                            {
                                Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        Array.Empty<string>()
                    }
                });
            });
        }

        /// <summary>
        /// 配置Swagger中间件
        /// </summary>
        /// <param name="app">Web应用程序</param>
        private static void ConfigureSwaggerMiddleware(WebApplication app)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "JGSY CMS LowCode Platform API V1");
                c.RoutePrefix = "swagger";
            });
        }

        /// <summary>
        /// 加载额外的配置文件
        /// </summary>
        /// <param name="builder">Web应用程序构建器</param>
        private static void LoadAdditionalConfigurationFiles(WebApplicationBuilder builder)
        {
            var configFiles = new[]
            {
                "appsettings.Logging.json",
                "appsettings.Database.json", 
                "appsettings.Cache.json",
                "appsettings.Security.json",
                "appsettings.SMS.json",
                "appsettings.Storage.json",
                "appsettings.Performance.json"
            };

            foreach (var configFile in configFiles)
            {
                builder.Configuration.AddJsonFile(configFile, optional: true, reloadOnChange: true);
            }

            // Also add environment-specific versions of these files
            var environment = builder.Environment.EnvironmentName;
            foreach (var configFile in configFiles)
            {
                var envConfigFile = configFile.Replace(".json", $".{environment}.json");
                builder.Configuration.AddJsonFile(envConfigFile, optional: true, reloadOnChange: true);
            }
        }
    }
}
